import axios from 'axios'

import { Message } from 'view-design'
import config from '@/config'

class HttpRequest {
  constructor(baseUrl = config.baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      withCredentials: true, // 允许携带cookie
      changeOrigin: true, // 允许跨域
      headers: {
        'Content-type': 'application/json'
      },
      timeout: 600000
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        this.queue[url] = true
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url)
        const _data = res.data || {}
        const { code, msg } = _data
        if (code === 200) {
          return res.data
        } else if (code === 1) {
          Message.error(msg || '暂不支持此数据')
          return Promise.reject(_data)
        } else {
          return Promise.reject(_data)
        }
      },
      error => {
        this.destroy(url)
        const { status, data: { message } } = error.response
        switch (status) {
          case 401:
            window.location.href = '/api/login'
            break
          default:
            Message.error(message || '网络连接出错，请稍后再试！')
            break
        }

        return Promise.reject(error)
      }
    )
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
